/*
 * The MIT License
 *
 * Copyright 2014 Venkat Ram Akkineni.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package org.netbeans.modules.tfsnb.tfvc.workspace;

import com.microsoft.tfs.core.TFSTeamProjectCollection;
import com.microsoft.tfs.core.clients.versioncontrol.VersionControlClient;
import com.microsoft.tfs.core.clients.versioncontrol.soapextensions.WorkingFolder;
import com.microsoft.tfs.core.clients.versioncontrol.soapextensions.Workspace;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JToolBar;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.netbeans.modules.tfsnb.tfvc.workingfolder.NewWorkingFolderMappingPanel;
import org.netbeans.modules.tfsnb.tfvc.workingfolder.WorkingFolderWizardAction;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.util.ImageUtilities;
import org.openide.util.NbBundle;
import org.openide.util.RequestProcessor;

/**
 *
 * @author Venkat Ram Akkineni
 */
public class WorkingFoldersMappingsPanel extends javax.swing.JPanel {
    
    /**
     * Creates new form WorkingFoldersMappingsPanel
     */
    public WorkingFoldersMappingsPanel(final VersionControlClient vcc,
            final TFSTeamProjectCollection teamProjectCollection) {
        this.vcc = vcc;
        this.teamProjectCollection = teamProjectCollection;
        initComponents();
//        setupCellEditors();
        addButtons(workingFoldersToolBar);
        controller = new WorkingFoldersMappingController(this);
        workingFoldersTable.setModel(workingFoldersMappingTableModel);        
    }
    
    public WorkingFoldersMappingsPanel(final VersionControlClient vcc,
            final TFSTeamProjectCollection teamProjectCollection,
            final String displayName) {
        this(vcc, teamProjectCollection);
        
        if(displayName != null) {
            showWorkingFolders(displayName);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
     * content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        workingFoldersScrollPane = new javax.swing.JScrollPane();
        workingFoldersTable = new javax.swing.JTable();
        workingFoldersToolBar = new javax.swing.JToolBar();
        workingFoldersTitleLabel = new javax.swing.JLabel();

        setBorder(javax.swing.BorderFactory.createEtchedBorder());

        workingFoldersTable.setModel(new WorkingFoldersMappingTableModel());
        workingFoldersScrollPane.setViewportView(workingFoldersTable);

        workingFoldersToolBar.setRollover(true);

        org.openide.awt.Mnemonics.setLocalizedText(workingFoldersTitleLabel, org.openide.util.NbBundle.getMessage(WorkingFoldersMappingsPanel.class, "WorkingFoldersMappingsPanel.workingFoldersTitleLabel.text")); // NOI18N
        workingFoldersToolBar.add(workingFoldersTitleLabel);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(workingFoldersToolBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(workingFoldersScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 643, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(workingFoldersToolBar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(workingFoldersScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void addButtons(JToolBar toolbar) {        
        JButton add = createButton("plus.png", "ConfiguredWorkspacesTablePanel.addWorkspace", "ConfiguredWorkspacesTablePanel.addWorkspace");
        add.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                NewWorkingFolderMappingPanel mappingPanel = new NewWorkingFolderMappingPanel(vcc, teamProjectCollection);
                final DialogDescriptor dd = new DialogDescriptor(mappingPanel, "");
                Object result = DialogDisplayer.getDefault().notify(dd);
            }
            
        });
        toolbar.add(add);
        
        JButton remove = createButton("minus.png", "ConfiguredWorkspacesTablePanel.removeWorkspace", "ConfiguredWorkspacesTablePanel.removeWorkspace");
        remove.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                controller.remove();
            }
        });
        toolbar.add(remove);
        
        JButton edit = createButton("edit.png", "ConfiguredWorkspacesTablePanel.editWorkspace", "ConfiguredWorkspacesTablePanel.editWorkspace");
        edit.addActionListener(new WorkingFolderWizardAction(vcc, teamProjectCollection));
        toolbar.add(edit);
        
        JButton refresh = createButton("refresh.png", "ConfiguredWorkspacesTablePanel.refreshList", "ConfiguredWorkspacesTablePanel.refreshList");
        refresh.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                controller.refresh();
            }
        });
        toolbar.add(refresh);
    }
        
        /**
     * 
     * @param iconBase
     * @param altTextKey
     * @param tooltipTextKey
     * @return 
     */
    private JButton createButton(final String iconBase, final String altTextKey, final String tooltipTextKey) {
        JButton button = new JButton();
        
        String altText = NbBundle.getMessage(ConfiguredWorkspacesTablePanel.class, altTextKey);
        String tooltipText = NbBundle.getMessage(ConfiguredWorkspacesTablePanel.class, tooltipTextKey);
        ImageIcon icon = ImageUtilities.loadImageIcon(RESOURCE_DIR + iconBase, true);
        if(icon != null) {
            button.setIcon(icon);
        } else {
            button.setText(altText);
        }
        button.setToolTipText(altText);
        return button;
    }

    private void setupCellEditors() {
        TableColumn tableColumn = workingFoldersTable.getColumnModel().getColumn(0);
        JComboBox comboBox = new JComboBox();
        comboBox.addItem("Active");
        comboBox.addItem("Inactive");
        tableColumn.setCellEditor(new DefaultCellEditor(comboBox));
    }
    
    private void removeAllRows() {
        for (int i = 0; i < workingFoldersMappingTableModel.getRowCount(); i++) {
            workingFoldersMappingTableModel.removeRow(i);
        }
    }

    public void reRenderTable(final String displayName) {
        showWorkingFolders(displayName);
    }

    private void showWorkingFolders(final String displayName) {
        final String message = NbBundle.getMessage(WorkingFoldersMappingsPanel.class, 
                "WorkingFoldersMappingsPanel.updatingWorkingFoldersProgressBar");
        
        RequestProcessor.getDefault().post(new Runnable() {
            @Override
            public void run() {
                final ProgressHandle progress = ProgressHandleFactory.createHandle(message);
                progress.start();
                
                final WorkingFolder[] workingFolders = getWorkspaceMappingFolders(displayName);
                removeAllRows(); // Delete all existing rows and redraw
                for(WorkingFolder wf: workingFolders) {
                    workingFoldersMappingTableModel.addRow(new Object[]{ wf.getServerItem(), wf.getLocalItem() });
                }
                
                progress.finish();
            }
        });
    }
    
    
    public WorkingFolder[] getWorkspaceMappingFolders(final String displayName) {
        String[] workspaceDetails = displayName.split(";");
        Workspace workspace = vcc.getWorkspace(workspaceDetails[0], workspaceDetails[1]);        
        return workspace.getFolders();
    }

    private static class WorkingFoldersMappingTableModel extends DefaultTableModel {
        
        Class[] types = new Class [] {
            java.lang.String.class, java.lang.String.class, java.lang.String.class
        };
        
        private static final int numberOfColumns = 2;
        
        static {
            // Look up numberOfColumns
        }

        public WorkingFoldersMappingTableModel() {
            super(new String[0][2],
            new String [] {
//                NbBundle.getMessage(WorkingFoldersMappingsPanel.class, "WorkingFoldersMappingsPanel.Table.status"), 
                NbBundle.getMessage(WorkingFoldersMappingsPanel.class, "WorkingFoldersMappingsPanel.Table.sourceControlFolder"),
                NbBundle.getMessage(WorkingFoldersMappingsPanel.class, "WorkingFoldersMappingsPanel.Table.localFolder")
            });
        }
        
        @Override
        public int getColumnCount() {
            return numberOfColumns;
        }
        
        @Override
        public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return true;
        }
        
    }
    
    private final VersionControlClient vcc;
    private TFSTeamProjectCollection teamProjectCollection;
    private final WorkingFoldersMappingTableModel workingFoldersMappingTableModel = new WorkingFoldersMappingTableModel();
    private static final String RESOURCE_DIR = "org/netbeans/modules/tfsnb/tfvc/workspace/";
    private WorkingFolder[] workingFolders;
    private final WorkingFoldersMappingController controller;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane workingFoldersScrollPane;
    private javax.swing.JTable workingFoldersTable;
    private javax.swing.JLabel workingFoldersTitleLabel;
    private javax.swing.JToolBar workingFoldersToolBar;
    // End of variables declaration//GEN-END:variables

    

}
